package entrata;

import classi.utente;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author sestari
 */
public class insertfoto extends HttpServlet {

    /**
     * Generazione del codice HTML
     *
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void html(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("<!DOCTYPE html>   ");
            out.println("<html>  ");
            out.println("    <head>  ");
            out.println("        <title>Inserire FOTO</title> ");
            out.println("    </head>  ");
            out.println("    <body>  ");
            out.println("        <form action=\"insertfoto\" enctype=\"multipart/form-data\"  method=\"POST\" > ");
            out.println("            <table border=\"1\"> ");



            out.println("                <tr> ");
            out.println("                    <td bgcolor=\"#DEDFF7\"> ");
            out.println("                 Foto:");
            out.println("                    </td> ");
            out.println("                    <td bgcolor=\"white\">  ");

            out.println("                   <input type=\"file\" name=\"arquivo\" /> ");

            out.println("                    </td> ");
            out.println("                </tr> ");

            out.println("                <tr>       ");
            out.println("                    <td> ");
            out.println("                        <input type=\"submit\" name=\"inviare\" value=\"creare\"/> ");
            out.println(" ");
            out.println("                        </form> ");
            out.println("                    </td> ");
            out.println("                <form action=\"index.html\" method=\"post\">  ");
            out.println("                    <td>  ");
            out.println("                        <input type=\"submit\" name=\"tornare\" value=\"Pagina iniziale\"/> ");
            out.println("                    </td>                    ");
            out.println("                </form>  ");
            out.println("                </tr>  ");
            out.println(" ");
            out.println("            </table> ");
            out.println("    </body>  ");
            out.println("</html>  ");

        } finally {
            out.close();
        }
    }

    /**
     * Classe utilizzata per fare l'upload della foto
     *
     * @param request
     * @param response
     * @param id
     * @throws FileUploadException
     * @throws Exception
     */
    public void upLoad(HttpServletRequest request, HttpServletResponse response, Integer id) throws FileUploadException, Exception {
        File tmpDir, destinationDir;
        String realPath = getServletContext().getRealPath("/foto");

        //Destinazione della foto
        destinationDir = new File(realPath);
        tmpDir = new File("/foto");


        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB

        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();

                if (item.isFormField()) {
                } else {
                    File file = new File(destinationDir, id + ".jpg");
                    item.write(file);


                    //Inserisce l'indirizzo della foto
                    ServletContext sc = getServletContext();
                    Connection con = (Connection) sc.getAttribute("con");
                    String comand = "UPDATE Persone SET foto = ? WHERE ID = ?";
                    PreparedStatement ps;

                    ps = (PreparedStatement) con.prepareStatement(comand);

                    ps.setString(1, "/foto/" + id + ".jpg");
                    ps.setInt(2, id);

                    ps.executeUpdate();


                }

            }
        } catch (FileUploadException ex) {
            log("Error encountered while parsing the request", ex);
        } catch (Exception ex) {
            log("Error encountered while uploading file", ex);
        }

    }

    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        html(request, response);
    }

    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        utente uten = (utente) session.getAttribute("user");
        try {
            upLoad(request, response, uten.getId());
        } catch (FileUploadException ex) {
            Logger.getLogger(insertfoto.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(insertfoto.class.getName()).log(Level.SEVERE, null, ex);
        }

        response.sendRedirect("welcome");
    }
}
